package com.ebupt.migu.music.propagate.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ebupt.migu.common.dto.MiguSubCompanyCampDto;
import com.ebupt.migu.music.common.constants.StrategyConstants;
import com.ebupt.migu.music.common.entity.Page;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.sms.Sender;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.common.util.HttpUtils;
import com.ebupt.migu.music.common.util.JsonUtils;
import com.ebupt.migu.music.megamarket.mapper.MegamarketMapper;
import com.ebupt.migu.music.propagate.mapper.PropagateApproveMapper;
import com.ebupt.migu.music.propagate.mapper.PropagateInfoMapper;
import com.ebupt.migu.music.propagate.mapper.PropagateStrategyMapper;
import com.ebupt.migu.music.propagate.pojo.dto.MiguPropagateApproveDto;
import com.ebupt.migu.propagate.PropagateInfo;
import com.ebupt.migu.propagate.PropagateStrategy;
import com.ebupt.migu.music.propagate.service.PropagateApproveService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class propagateApproveServiceImpl implements PropagateApproveService {

    @Resource
    private PropagateApproveMapper propagateApproveMapper;

    @Resource
    private PropagateStrategyMapper propagateStrategyMapper;

    @Resource
    private PropagateInfoMapper   propagateInfoMapper;





    @Autowired
    private MegamarketMapper megamarketMapper;



    @Value("${megamarket.ip}")
    private String MEGAMARKET_IP;

    @Value("${megamarket.subCompanyCampSync2Marketing}")
    private String MEGAMARKET_SUBCOMPANYCAMPSYNC2MARKETING;



    @Override
    public ResultObject queryList(Map<String, Object> params) {

        ResultObject res = new ResultObject();
        List<HashMap<String, Object>> datas = new ArrayList<>();
        Integer total;
        // 策略状态：1-待审核；2-已驳回；3-未开始；4-进行中；5-已终止；6-已结束；7-已删除
        List<Byte> tacStatus = new ArrayList<>();
        // 获取指定的审批状态
        // 审批状态：1-待审批；2-已通过；3-已驳回；
        String approveStatus = String.valueOf(params.get("status"));
        switch (approveStatus) {
            case "1":
                tacStatus.add(Byte.valueOf("1"));
                break;
            case "2":
                tacStatus.add(Byte.valueOf("2"));
                break;
            case "3":
                tacStatus.add(Byte.valueOf("3"));
                tacStatus.add(Byte.valueOf("4"));
                tacStatus.add(Byte.valueOf("5"));
                tacStatus.add(Byte.valueOf("6"));
                break;
        }
        params.put("tacStatus", tacStatus);
        total = propagateApproveMapper.queryApproveRecordsCount(params);
        // ${pageStart} , ${rows}
        int pageStart = Integer.parseInt(params.get("pageStart").toString());
        int rows = Integer.parseInt(params.get("rows").toString());
        params.put("pageStart",(pageStart-1)*rows);
        params.put("rows",pageStart*rows);
        datas = propagateApproveMapper.queryApproveRecords(params);
        for (HashMap<String, Object> data : datas) {
              List<HashMap<String, Object>> ranks = propagateApproveMapper.queryRankDetail(data);
             for (HashMap<String, Object> map : ranks) {
                String s = map.get("status").toString();
                if (s.equals("1")) {
                    data.put("approverId",map.get("approverId") );
                    data.put("approverName", map.get("approverName"));
                    map.put("isr","1");
                    break;
                }else
                {
                    data.put("approverId", null);
                    data.put("approverName",null );
                    map.put("isr","0");
                }
            }
            data.put("ranks", ranks);
            String status=null;
            //执行状态：1-待审核；2-已驳回；3-未开始；4-进行中；5-已中止；6-已结束；7-已删除；8-待提审；9-大营销平台审核中
            switch (data.get("executeStatus").toString()) {
                case "1":
                    status="1";
                    break;
                case "2":
                    status="2";
                    break;
                case "3":
                    status="3";
                    break;
                case "4":
                    status="3";
                    break;
                case "5":
                    status="3";
                    break;
                case "6":
                    status="3";
                    break;
            }
            data.put("status", status);

        }
        // 分页
        Page<HashMap<String, Object>> page = new Page<>();
        page.setTotal(total);
        page.setData(datas);
        res.setMsg("查询审批列表成功");
        res.setData(page);
        return res;
    }

    @Override
    public ResultObject queryDetail(Map<String, Object> params) {
        ResultObject res = new ResultObject();
        HashMap<Object, Object> returnMap = new HashMap<>();
        QueryWrapper<PropagateStrategy> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(true,PropagateStrategy::getStrategyId,params.get("strategyId").toString());
        PropagateStrategy strategy= propagateStrategyMapper.selectOne(queryWrapper);
        List<HashMap<String, Object>>  approves= propagateApproveMapper.queryRankDetail(params);
        final boolean[] b = {true};
        approves.forEach(map -> {
            String s = map.get("status").toString();
            if (b[0] &&s.equals("1")){
                map.put("isr","1");
                b[0] =false;
            }else {
                map.put("isr","0");
            }
        });
        returnMap.put("strategy",strategy);
        returnMap.put("approve",approves);
        res.setData(returnMap);
        return res;
    }

    @Override
    public ResultObject doApprove(Map<String, Object> params) {
        List<HashMap<String, Object>>  approves= propagateApproveMapper.queryRankDetail(params);
        ResultObject res = new ResultObject();
        boolean present = approves.stream().anyMatch(map -> map.get("approverId").equals(params.get("approverId")));
        // 验证是否是超管或者记录指定审批人
        if (!("1").equals(params.get("isAuditor")) && !("1").equals(params.get("isAdmin"))
                && !present ) {
            res.setCode(StatusEnum.OPERATE_LIMITED.getCode());
            res.setMsg("当前用户无审批权");
            return res;
        }
        // 审批状态：1-待审批；2-已驳回；3-已通过；
        String Status = String.valueOf(params.get("status"));
        HashMap<String, Object>  approverMap= approves.stream().filter(map ->params.get("rank").equals(map.get("rank").toString())).findFirst().get();
        // 新增审批记录
        HashMap<String, Object>  record = new HashMap<>();
        record.put("rid",approverMap.get("id"));
        record.put("status",Status);
        record.put("remark",params.get("remark"));
        propagateApproveMapper.createApproverDetail(record);
        UpdateWrapper<PropagateStrategy> updateWrapper = new UpdateWrapper<>();
        // 修改策略状态
        switch (Status) {
            //通过则判断是否为最后一个审核
            case "2":
                updateWrapper.lambda()
                        .set(true,PropagateStrategy::getExecuteStatus,2)
                        .eq(true,PropagateStrategy::getStrategyId,params.get("strategyId"));
                propagateStrategyMapper.update(null,updateWrapper);
                break;
            //不通过则直接修改状态
            case "3":
                HashMap<String, Object> last = approves.get(approves.size() - 1);
                if(last.get("rank").equals(approverMap.get("rank"))){
                    updateWrapper.lambda()
                            .set(true,PropagateStrategy::getExecuteStatus,3)
                            .eq(true,PropagateStrategy::getStrategyId,params.get("strategyId"));
                    propagateStrategyMapper.update(null,updateWrapper);
                    //查询当前策略明细
                    QueryWrapper<PropagateStrategy> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda()
                            .eq(true,PropagateStrategy::getStrategyId,params.get("strategyId").toString());
                    PropagateStrategy strategy= propagateStrategyMapper.selectOne(queryWrapper);
                    //推送
                    this.push(strategy);
                }
                break;
        }
        res.setMsg("审核成功");
        return res;
    }

    @Override
   public   void    push(PropagateStrategy strategy){
       MiguPropagateApproveDto miguSubCompanyCampDto = new MiguPropagateApproveDto();
       miguSubCompanyCampDto.setBlackUser(0);
       miguSubCompanyCampDto.setCampsegDesc(strategy.getRemark() == null ? "1":(strategy.getRemark()));
       String campsegId = strategy.getStrategyId();
       miguSubCompanyCampDto.setCampsegId(campsegId);
       miguSubCompanyCampDto.setCampsegName(strategy.getStrategyName());
       // 使用服务云自己的用户id
       miguSubCompanyCampDto.setCreateLoginName(strategy.getCreatorId());

       // 父id，要与策略id不一致
       String campsegPid =
           strategy.getStrategyId() + (int)((Math.random() * 9 + 1) * Math.pow(10, 4 - 1));
       miguSubCompanyCampDto.setCampsegPid(campsegPid);
       // 短信下发去重天数，暂时不用去重
       miguSubCompanyCampDto.setDistictDays(0);

       // 方法4：
       Calendar cal=Calendar.getInstance();
       int h=cal.get(Calendar.HOUR_OF_DAY);
       int mi=cal.get(Calendar.MINUTE)+10;
       int s=cal.get(Calendar.SECOND);
       miguSubCompanyCampDto.setEndDate(strategy.getEndTime()+" "+h+":"+mi+":"+s);
       miguSubCompanyCampDto.setStartDate(strategy.getStartTime()+" 59:59:59");
       HashMap<String, String> megamarket =
               megamarketMapper.qryMegamarketInfoByID(Integer.valueOf(String.valueOf(strategy.getSendPort())));
       // miguSubCompanyCampDto.setAdivId(StrategyConstants.MEGAMARKET_ADIVID);
       miguSubCompanyCampDto.setAdivId(megamarket.get("adivId"));
       // miguSubCompanyCampDto.setShortUrl(params.get("shortUrl").toString());

       List<PropagateInfo> propagateInfos = propagateInfoMapper.qryByStrategyId(strategy.getStrategyId());
       PropagateInfo propagateInfo = propagateInfos.get(0);
       // 短信内容不能超过100
       miguSubCompanyCampDto.setSmsContent(propagateInfo.getSmsContent().length() >= 100
               ? propagateInfo.getSmsContent().substring(0, 99) : propagateInfo.getSmsContent());
       miguSubCompanyCampDto.setSubCompanyCode(StrategyConstants.MEGAMARKET_SUBCOMPANYCODE);
       // 大营销账户组编码，由大营销平台定义
       miguSubCompanyCampDto.setUserGroupId(StrategyConstants.MEGAMARKET_USERGROUPID);
       miguSubCompanyCampDto.setCampsegStatId(StrategyConstants.MEGAMARKET_CAMPSEGSTATID_CHECKING);

       log.info("{}发送的body MiguPropagateApproveDto:{}", strategy.getStrategyId(),
               miguSubCompanyCampDto.toString());

       String url = MEGAMARKET_IP + MEGAMARKET_SUBCOMPANYCAMPSYNC2MARKETING;

       log.info("服务端URL: {}", url);

       String response = null;
       try {
           response = HttpUtils.doPost(url, JsonUtils.obj2Json(miguSubCompanyCampDto), null);
       } catch (IOException e) {
           throw new RuntimeException(e);
       }
       log.info("HTTP请求结果：{}", response);
       Map responseMap = JsonUtils.json2Obj(response, HashMap.class);
       if (!responseMap.get("status").toString().equals("SUCCESS")) {
           try {
               String[] tels = new String[1];
               tels[0] = String.valueOf(strategy.getCreatorPhone());
               String[] vals = new String[3];
               vals[0] = String.valueOf(strategy.getStrategyName());
               vals[1] = "短信";
               vals[2] = "大营销平台默认审核失败";
               Sender.sendSMS("20100066", tels, vals);
           } catch (Exception e) {
               log.error("发送通知短信失败：{}", strategy);
               throw new MyException(StatusEnum.SMS_SEND_MEGAMARKET_AUDIT, "同步到大营销平台接口调用异常");
           }
           throw new MyException(StatusEnum.SMS_SEND_MEGAMARKET_AUDIT, "同步到大营销平台接口调用异常");
       }

   }

}
